using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ECommerce.Library;
using AutoGear.BLL;
using System.IO;
using eShop.Model;

/// <summary>
/// Summary description for CategoryFileAccessUtility
/// </summary>
public sealed class CategoryFileAccessUtility : FileAccessUtility
{
    private const string _categoryRootPath = "~/";
    //private const string _categoryTemplateFilePath = "~/templates/category-template.txt";
    //private const string _categoryTemplateCsFilePath = "~/templates/category-template-cs.txt";
    private const string _categoryImageRootPath = "~/upload/images/category/";
    private const string _categoryBannerImageRootPath = "~/upload/images/category_banner/";
    private const int _maxImageWidth = 129;
    private const int _maxBannerImageWidth = 630; //770;
    private const int _maxBannerImageWidthWithNoProduct = 650;

    private CategoryFileAccessUtility() { }

    public static Category CreateCategoryFiles(Category newCategory, string logoTemporaryFilePath, string categoryBannerTemporaryFilePath)
    {
        // check whether parent category folder exists,
        // otherwise throw invalid operation exception
        // check existing folder with same name
        // if exist, delete it, otherwise create
        // a folder with category name and 
        // create a aspx file Default.aspx int this
        // folder and returns the category url

        string newCategoryPath = GenerateNewCategoryPath(newCategory);
        string cleanCategoryName = SiteUtility.CleanCategoryName(newCategory.CategoryName).ToLower();

        //if (HttpContext.Current.Server.MapPath(newCategoryPath) == HttpContext.Current.Server.MapPath(_categoryRootPath))
        //{
        //    throw new IOException("Access denied in modifying Root Folder for category in CategoryFileAccessUtility.CreateCategoryFiles");
        //}
        //if (Directory.Exists(HttpContext.Current.Server.MapPath(newCategoryPath)))
        //{
        //    DeleteFolder(newCategoryPath);
        //}

        //CreateFolder(newCategoryPath);
        try
        {
            FileInfo logoInfo = new FileInfo(HttpContext.Current.Server.MapPath(logoTemporaryFilePath));
            if (logoInfo.Exists)
            {
                string logoFileName = cleanCategoryName + logoInfo.Extension;
                newCategory.CategoryImageUrl = UploadCategoryLogo(logoTemporaryFilePath, logoFileName);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }


        try
        {
            FileInfo bannerInfo = new FileInfo(HttpContext.Current.Server.MapPath(categoryBannerTemporaryFilePath));
            if (bannerInfo.Exists)
            {
                string bannerFileName = cleanCategoryName + bannerInfo.Extension;
                newCategory.CategoryBannerImageUrl = UploadCategoryBanner(categoryBannerTemporaryFilePath, bannerFileName);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

        //CreateTemplateFiles(newCategory);

        return newCategory;
    }


    public static string UploadCategoryLogo(string temporaryImagePath, string logoFileName)
    {
        try
        {
            FileInfo logoInfo = new FileInfo(HttpContext.Current.Server.MapPath(temporaryImagePath));
            if (logoInfo.Exists)
            {
                logoFileName = SiteUtility.CleanCategoryName(logoFileName.ToLower()) + logoInfo.Extension;
                logoFileName = RandomizeImageFileName(logoFileName);

                string outputFilePath = _categoryImageRootPath + logoFileName;
                System.Drawing.Size originalImageDimension = ImageResizer.GetImageDimension(temporaryImagePath);
                string bigImagePath = null;
                ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, true, "_max");
                if (originalImageDimension.Width > _maxImageWidth)
                {
                    bigImagePath = ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, _maxImageWidth, true, "_big");
                }
                else
                {
                    bigImagePath = ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, true, "_big");
                }
                FileAccessUtility.DeleteFile(temporaryImagePath);
                return bigImagePath;
            }
            else
            {
                throw new Exception();
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public static bool DeleteCategoryLogo(string logoFileName)
    {
        try
        {
            FileInfo logoInfo = new FileInfo(HttpContext.Current.Server.MapPath(logoFileName));
            if (logoInfo.Exists)
            {
                return DeleteFile(logoFileName);
            }
            return false;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }



    public static string UploadCategoryBanner(string temporaryImagePath, string logoFileName)
    {
        try
        {
            FileInfo logoInfo = new FileInfo(HttpContext.Current.Server.MapPath(temporaryImagePath));
            if (logoInfo.Exists)
            {
                logoFileName = SiteUtility.CleanCategoryName(logoFileName.ToLower()) + logoInfo.Extension;
                logoFileName = RandomizeImageFileName(logoFileName);

                string outputFilePath = _categoryBannerImageRootPath + logoFileName;
                System.Drawing.Size originalImageDimension = ImageResizer.GetImageDimension(temporaryImagePath);
                string bigImagePath = null;
                string maxImagePath = null;
                maxImagePath= ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, true, "_max");

                if (originalImageDimension.Width > _maxBannerImageWidthWithNoProduct)
                {
                    ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, _maxBannerImageWidthWithNoProduct, true, "_noproduct");
                }
                else
                {
                    ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, true, "_noproduct");
                }
                
                if (originalImageDimension.Width > _maxBannerImageWidth)
                {
                    bigImagePath = ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, _maxBannerImageWidth, true, "_big");
                }
                else
                {
                    bigImagePath = ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, true, "_big");
                }                

                FileAccessUtility.DeleteFile(temporaryImagePath);
                return maxImagePath;
            }
            else
            {
                throw new Exception();
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public static bool DeleteCategoryBanner(string logoFileName)
    {
        try
        {
            FileInfo logoInfo = new FileInfo(HttpContext.Current.Server.MapPath(logoFileName));
            if (logoInfo.Exists)
            {
                return DeleteFile(logoFileName);
            }
            return false;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public static bool DeleteCategoryFiles(Category oldCategory)
    {
        // check whether the category folder exists,
        // if exists delete it.
        try
        {
            //if (HttpContext.Current.Server.MapPath(oldCategory.CategoryUrl) == HttpContext.Current.Server.MapPath(_categoryRootPath))
            //{
            //    throw new IOException("Access denied in modifying Root Folder for category in CategoryFileAccessUtility.CreateCategoryFiles");
            //}
            if (Directory.Exists(HttpContext.Current.Server.MapPath(oldCategory.CategoryUrl)))
            {
                return DeleteFolder(oldCategory.CategoryUrl);
            }
            else
                return true;
        }
        catch (Exception e)
        {
            throw e;
        }
    }

    public static string UpdateCategoryFiles(string oldCategoryPath, Category newCategory)
    {
        string newCategoryPath = GenerateNewCategoryPath(newCategory);
        if (HttpContext.Current.Server.MapPath(newCategoryPath) == HttpContext.Current.Server.MapPath(_categoryRootPath))
        {
            throw new IOException("Access denied in modifying Root Folder for category in CategoryFileAccessUtility.CreateCategoryFiles");
        }
        if (Directory.Exists(HttpContext.Current.Server.MapPath(oldCategoryPath)))
        {
            if (MoveFolder(oldCategoryPath, newCategoryPath))
            {
                CreateTemplateFiles(newCategory);
            }
            else
            {
                throw new IOException("Failed to rename folder for category in CategoryFileAccessUtility.CreateCategoryFiles");
            }
        }
        return newCategoryPath;
    }

    private static string RandomizeImageFileName(string plainName)
    {
        if (string.IsNullOrEmpty(plainName))
            throw new ArgumentNullException("plainName in CategoryAccessUtility.RandomizeImageFileName()");

        int indexOfDot = plainName.LastIndexOf('.');
        string extension = plainName.Substring(indexOfDot);

        if (plainName.Contains("_"))
        {
            int indexOfGuid = plainName.LastIndexOf('_');

            if (indexOfGuid > 0 && indexOfGuid < plainName.Length)
            {
                string actualName = plainName.Substring(0, indexOfGuid + 1);
                return actualName + Guid.NewGuid().ToString().Replace("-", "") + extension;
            }
        }
        else
        {
            if (indexOfDot > 0 && indexOfDot < plainName.Length)
            {
                string actualName = plainName.Substring(0, indexOfDot + 1);
                return actualName + Guid.NewGuid().ToString().Replace("-", "") + extension;
            }
        }

        return null;
    }

    public static string GenerateNewCategoryPath(Category newCategory)
    {
        string newCategoryPath;
        if (newCategory == null)
        {
            throw new ArgumentNullException("newCategor in CategoryFileAccessUtility.GenerateNewCategoryPath");
        }
        if (string.IsNullOrEmpty(newCategory.CategoryName))
        {
            throw new ArgumentNullException("newCategory.CategoryUrl in CategoryFileAccessUtility.GenerateNewCategoryPath");
        }
        string cleanCategoryName = SiteUtility.CleanCategoryName(newCategory.CategoryName).ToLower();
        if (newCategory.ParentCategory == null)
        {
            newCategoryPath = _categoryRootPath + cleanCategoryName + "/";
        }
        else
        {
            newCategoryPath = newCategory.ParentCategory.CategoryUrl + cleanCategoryName + "/";
        }
        return newCategoryPath;
    }

    public static void CreateTemplateFiles(Category newCategory)
    {
        //if (File.Exists(HttpContext.Current.Server.MapPath(_categoryTemplateFilePath)))
        //{
        //    try
        //    {
        //        string cleanCategoryName = SiteUtility.CleanCategoryName(newCategory.CategoryName.ToLower());
        //        string newCategoryPath = GenerateNewCategoryPath(newCategory);

        //        TextReader reader = new StreamReader(HttpContext.Current.Server.MapPath(_categoryTemplateFilePath));
        //        string templateContent = reader.ReadToEnd();
        //        templateContent = templateContent.Replace("<##CategoryClassName##>", (cleanCategoryName.Replace('-', '_')).ToLower());
        //        templateContent = templateContent.Replace("<##CategoryId##>", newCategory.CategoryId.ToString());
        //        if (!CreateFile(newCategoryPath + "default.aspx", templateContent))
        //        {
        //            throw new IOException("Failed to create file for category in CategoryFileAccessUtility.CreateCategoryFiles");
        //        }

        //        reader = new StreamReader(HttpContext.Current.Server.MapPath(_categoryTemplateCsFilePath));
        //        templateContent = reader.ReadToEnd();
        //        templateContent = templateContent.Replace("<##CategoryClassName##>", cleanCategoryName.Replace('-', '_').ToLower());
        //        templateContent = templateContent.Replace("<##CategoryId##>", newCategory.CategoryId.ToString());
        //        bool IsCategoryPage = string.IsNullOrEmpty(newCategory.CategoryBannerImageUrl) ? false : true;
        //        templateContent = templateContent.Replace("<##IsCategoryPage##>", IsCategoryPage.ToString().ToLower());
        //        if (!CreateFile(newCategoryPath + "default.aspx.cs", templateContent))
        //        {
        //            throw new IOException("Failed to create file for category in CategoryFileAccessUtility.CreateCategoryFiles");
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}
        //else
        //{
        //    throw new IOException("_categoryTemplateFilePath in CategoryFileAccessUtility.CreateCategoryFiles");
        //}
    }
    public static void RenameCategory(string OldCatPath, string NewCatPath)
    {
        //try
        //{
            //Directory.Move(HttpContext.Current.Server.MapPath(OldCatPath), HttpContext.Current.Server.MapPath(NewCatPath));
        //}
        //catch
        //{
        //    throw new IOException("RenameCategory in CategoryFileAccessUtility");
        //}
    }
}
